package com.qdd.freight.util;

import com.alibaba.fastjson.JSONObject;
import com.qdd.freight.constant.Constants;
import com.qdd.freight.entity.ReqContent;
import com.qdd.freight.enums.CacheKeyEnum;

import java.io.UnsupportedEncodingException;

/**
 * @author ：
 * @date ：2019-12-20 9:46
 * @description：
 * @modified By：
 * @version: 1.0
 */
public class Sign {

    public static ReqContent verify(String content, String lock, RedisUtil redisUtil) {
        ReqContent reqContent = null;
        String privateKey = redisUtil.get(CacheKeyEnum.PRIVATE_KEY.getCacheKey(), String.class);
        if (privateKey == null) {
            return null;
        }
        //秘钥解密
        try {
            lock = RSAUtils.privateDecrypt(lock, RSAUtils.getPrivateKey(privateKey));
        } catch (Exception e) {
            return null;
        }
        //密文解密
        try {
            content = UseAESUtil.decrypt(content, lock.getBytes(Constants.UTF8), Constants.AES_VI.getBytes(Constants.UTF8));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        //将参数转化实体
        reqContent = JSONObject.parseObject(content, ReqContent.class);
        if (reqContent == null || reqContent.getBase() == null || reqContent.getBase().getTime() == null || reqContent.getData() == null) {
            return null;
        }
        return reqContent;
    }

    public static String sign(ReqContent reqContent, String lock, RedisUtil redisUtil) {
        String privateKey = redisUtil.get(CacheKeyEnum.PRIVATE_KEY.getCacheKey(), String.class);
        if (privateKey == null) {
            return null;
        }
        try {
            return UseAESUtil.encrypt(JSONObject.toJSONString(reqContent), lock.getBytes(Constants.UTF8), Constants.AES_VI.getBytes(Constants.UTF8));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }
}
